﻿using Common.Configurations;
using Common.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.ComponentModel;

namespace WebAPI.Controllers;

/// <summary>
/// 上传文件
/// </summary>
[Description("上传管理")]
public class UploadController : ApiControllerBase
{

    private readonly IWebHostEnvironment _environment;
    private readonly IOptions<HostSettings> _hostSettingsOptions;

    public UploadController(
        IWebHostEnvironment environment, 
        IOptions<HostSettings> hostSettingsOptions)
    {
        _environment = environment;
        _hostSettingsOptions = hostSettingsOptions;
    }


    /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="purpose">用途</param>
    /// <returns></returns>
    [HttpPost("File/{purpose}")]
    [AllowAnonymous]
    [Description("上传文件")]
    public async Task<Result<dynamic>> UploadFile(string purpose)
    {
        var files = HttpContext.Request.Form.Files;

        if (files == null || files.Count == 0)
        {
            return await Result<dynamic>.FailureAsync(new string[] { "未选择文件" });
        }

        var file = files[0];

        if (file.Length == 0)
        {
            return await Result<dynamic>.FailureAsync(new string[] { "文件无效" });
        }

        // 生成文件名（使用Guid保证唯一性）
        string fileName = $"{Guid.NewGuid()}{GetFileExtension(file)}";

        // 构建文件保存路径（相对于wwwroot的路径）
        string relativePath = GetRelativeFilePath(file, purpose);

        // 获取wwwroot的物理路径
        string wwwrootPath = _environment.WebRootPath;

        // 构建文件完整保存路径
        string fullPath = Path.Combine(wwwrootPath, relativePath);

        // 创建目录（如果不存在）
        Directory.CreateDirectory(Path.GetDirectoryName(fullPath)!);

        // 将文件保存到磁盘
        using (var stream = new FileStream(fullPath, FileMode.Create))
        {
            await file.CopyToAsync(stream);
        }

        // 构建文件的URL路径（相对于应用程序的URL路径）
        string urlPath = "/" + relativePath.Replace("\\", "/");

        return await Result<dynamic>.SucceedAsync(new
        {
            Host = _hostSettingsOptions.Value.DomainName,
            Src = urlPath, // 返回相对于应用程序的URL路径
            FileName = fileName
        });
    }

    // 获取文件扩展名
    private string GetFileExtension(IFormFile file)
    {
        var extension = Path.GetExtension(file.FileName);
        if (string.IsNullOrEmpty(extension) || extension.Trim() == ".")
        {
            var contentType = file.ContentType;
            if (!string.IsNullOrEmpty(contentType))
            {
                var parts = contentType.Split('/');
                if (parts.Length == 2)
                {
                    extension = "." + parts[1];
                }
            }
        }
        return extension;
    }

    // 构建文件保存路径
    private string GetRelativeFilePath(IFormFile file,string purpose)
    {
        // 使用文件类型和日期构建文件夹层级结构
        string fileType = file.ContentType.Split("/")[0];
        string currentDate = DateTime.Now.ToString("yyyyMMdd");
        string fileName = $"{Guid.NewGuid()}{GetFileExtension(file)}";

        return Path.Combine("uploads", purpose, fileType, currentDate, fileName);
    }
}
